//
//  MBRecomIController.m
//  MiBaoTu
//
//  Created by mac004 on 2016/10/10.
//  Copyright © 2016年 com.caesartech15. All rights reserved.
//

#import "MBRecomIController.h"
#import "MBShowCell.h"
#import "MBDetailViewController.h"
#import "MBSpacePeopelViewController.h"
#import "MBSpaceNewsViewController.h"
#import "MBSongDetailController.h"
#import "MBShowForICell.h"
#import "MBLoginController.h"




#import "MBSongDetailForIController.h"
#import "MBDetailViewForIpadController.h"


@interface MBRecomIController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,MBShowForICellDelegate>
{
    int page;
    MBShowForICell *_showCell;
    BOOL selected;
    NSMutableArray      *_mutArr;
    NSDictionary        *temporarilyDic;//临时数据
    
    NSMutableArray      *_praiseListArr; //点赞列表
    float               nHeight;

}
@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;

@property(nonatomic,strong)NSMutableArray *dataArray;
@end

@implementation MBRecomIController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    page = 1;
    _mutArr = [[NSMutableArray alloc]init];
    _praiseListArr = [[NSMutableArray alloc]init];
    [self onCreateUI];

    
}
- (NSMutableArray *)dataArray
{
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)onCreateUI
{
    
          UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.flowLayout = flowLayout;
    
    _collectionView=[[UICollectionView alloc]initWithFrame:CGRectMake(0, 0,self.view.width ,(_viewHeight > 0 ? _viewHeight : self.view.height)) collectionViewLayout:self.flowLayout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    
    _collectionView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_collectionView];
    // 注册cell
    [_collectionView registerClass:[MBShowForICell class] forCellWithReuseIdentifier:@"cell"];
    
    [_collectionView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(onLoadNew)];
    [_collectionView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(onLoadMore)];
    
    if (nHeight > 0) {
        [self onUPdateUIForTable:nHeight];
    }

    if ([_sortStr isEqualToString:@"2"]) {
        [self onLoadNew];
    }
}

- (void)onUPdateUIForTable:(float)height
{
    nHeight = height;
    _collectionView.height = nHeight;
    [_collectionView reloadData];
}
#pragma mark - 加载数据
- (void)onLoadNew
{
    page = 1;
    [self loadData];
}

- (void)onLoadMore
{
    ++page;
    [self loadData];
}

- (void)loadData
{
    NSString *url = nil;
    UserModel *model = [UserManager standerDefult].userModel;
    
    if ([_sortStr isEqualToString:@"1"]) {
        //小编推荐
        url = [NSString stringWithFormat:FAMILYSHOW_FANSMORE_URL_PATH,model.UserID,[NSNumber numberWithInt:page]];
    }
    else if ([_sortStr isEqualToString:@"2"]) {
        //我的关注
        UserModel *model = [UserManager standerDefult].userModel;
        if (!model.UserID) {
            MBLoginController *registerLastVC = [[MBLoginController alloc] init];
            registerLastVC.formBaseViewCtrl = NSStringFromClass([self class]);
            [self.delegate pushSubViewController:registerLastVC];
            
            [_collectionView.header endRefreshing];
            [_collectionView.footer endRefreshing];
            return;
        }
        
        url = [NSString stringWithFormat:FAMILYSHOW_MYATTENTION_URL_PATH,model.UserID,[NSNumber numberWithInt:page]];
    } else {
        return;
    }
    
    [[HTTPManager standerDefault]AFGetRequest:url view:nil success:^(id json) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [_collectionView.header endRefreshing];
        [_collectionView.footer endRefreshing];
        
        if ([json[@"ret_code"] integerValue]==0) {
            NSArray *arr = json[@"data"];
            if (arr.count > 0) {
                if (page == 1) {
                    [_mutArr removeAllObjects];
                }
                [_mutArr addObjectsFromArray:arr];
            }
            [_collectionView reloadData];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [_collectionView.header endRefreshing];
        [_collectionView.footer endRefreshing];
        if (page == 1) {
            [_mutArr removeAllObjects];
        }
        [_collectionView reloadData];
    }];


}

#pragma mark - 加载数据
- (void)loadDB
{
    NSArray *praiseDBArr = [UserManager standerDefult].praiseListArr;
    [_praiseListArr removeAllObjects];
    if (praiseDBArr.count > 0) {
        for (NSDictionary *praiseDic in praiseDBArr) {
            NSString *praiseType = [praiseDic objectForKey:@"PraisedType"];
            if ([praiseType intValue] == 1) {
                //亲子秀
                NSString *idStr = [NSString stringWithFormat:@"%@",[praiseDic objectForKey:@"PraisedID"] ];
                NSDictionary *nDic = @{@"PraisedID":idStr};
                [_praiseListArr addObject:nDic];
            }
        }
    }
    [_collectionView reloadData];
}



- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    if ([_sortStr isEqualToString:@"1"]) {
//        [self onLoadNew];
//    }
//    [self loadDB];
    [self onLoadNew];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

#pragma mark - 结束编辑

#pragma Collectiondelegate
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _mutArr.count;
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 28*PERCEN;
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 28*PERCEN;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat width=(self.view.width-84*PERCEN)/2;
    return CGSizeMake(width, width/982*798);
}
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(28*PERCEN, 28*PERCEN, 28*PERCEN, 28*PERCEN);
}
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    
    _showCell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    _showCell.delegate = self;
    if (_mutArr.count > indexPath.row) {
        NSDictionary *dic = [_mutArr objectAtIndex:indexPath.row];
        BOOL isZan = NO;
        NSString*PraiseStatus=[NSString stringWithFormat:@"%@",dic[@"PraiseStatus"]];
        if ([PraiseStatus isEqualToString:@"0"]) {
            isZan=NO;
        }else{
            isZan=YES;
        }
        _showCell.isZan = isZan;
        _showCell.dataDic = dic;
    }

    return _showCell;
}
- (void)onSelectIconBtnWithView:(MBShowForICell *)view {
    
       NSLog(@"主播头像");
//    if ( self.delegate != nil && [self.delegate respondsToSelector:@selector(pushSubViewController:)]) {
//     
//        MBSpacePeopelViewController *spacePeopleVC = [[MBSpacePeopelViewController alloc] init];
//        [self.delegate pushSubViewController:spacePeopleVC];
//    }
       MBSpacePeopelViewController *spacePeopleVC = [[MBSpacePeopelViewController alloc] init];
    [self.navigationController pushViewController:spacePeopleVC animated:YES];
    _showCell = view;
}


-(void)onSelectPraiseBtnWithView:(MBShowForICell *)view withValue:(id)value {
    
 
    
    UserModel *model = [UserManager standerDefult].userModel;
    if (!model.UserID) {
        MBLoginController *registerLastVC = [[MBLoginController alloc] init];
        registerLastVC.formBaseViewCtrl = NSStringFromClass([self class]);
        [self.delegate pushSubViewController:registerLastVC];
        return;
    }
    
    if (![value isKindOfClass:[NSDictionary class]]) return;
    
    if (!model) return;
    
    //区分点赞或取消点赞
    NSString *idStr = [NSString stringWithFormat:@"%@",[value objectForKey:@"ID"]];
    
    NSString*PraiseStatus=[NSString stringWithFormat:@"%@",[value objectForKey:@"PraiseStatus"]];
    
    
    NSMutableDictionary *mutDic = [[NSMutableDictionary alloc]initWithDictionary:value];
    int indexMut = (int)[_mutArr indexOfObject:value];
    if ([PraiseStatus isEqualToString:@"1"]) {
        //取消点赞
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:FORUM_CANCEL_ZAN_URL_PATH,model.UserID,[value objectForKey:@"ID"],@1] view:nil success:^(id json) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            if ([json[@"ret_code"] integerValue]==0) {
                //取消点赞成功
                int index = (int)[_mutArr indexOfObject:value];
                if (_mutArr.count > index && index >= 0) {
                    MBShowForICell *cell = (MBShowForICell *)[_collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:[NSIndexPath indexPathForItem:index inSection:0]];
                    if ([cell isKindOfClass:[MBShowForICell class]]) {
                        [cell onUpdateZanBtAction:NO];
                    }
                }
                
//                //数据更新
//                [_praiseListArr removeObject:@{@"PraisedID":idStr}];
//                NSMutableArray *mutArr = [[NSMutableArray alloc]initWithArray:[UserManager standerDefult].praiseListArr];
//                for (NSDictionary *dic in mutArr) {
//                    NSString *praiseType = [dic objectForKey:@"PraisedType"];
//                    if ([praiseType intValue] == 1) {
//                        [[UserManager standerDefult].praiseListArr removeObject:dic];
//                    }
//                }
//                for (NSDictionary *dic in _praiseListArr) {
//                    NSMutableDictionary *mutDic = [[NSMutableDictionary alloc]initWithDictionary:dic];
//                    [mutDic setValue:@"1" forKey:@"PraisedType"];
//                    [[UserManager standerDefult].praiseListArr addObject:mutDic];
//                }
                //[mutDic setValue:[NSNumber numberWithInt:0] forKey:@"PraiseStatus"];
                
                
                [mutDic setValue:[NSNumber numberWithInt:([[value objectForKey:@"PraiseNum"] intValue]-1)] forKey:@"PraiseNum"];
                [mutDic setValue:@0 forKey:@"PraiseStatus"];
                NSLog(@"mutDci==%@",mutDic);
                
                if (indexMut < _mutArr.count && indexMut >= 0) {
                    [_mutArr replaceObjectAtIndex:indexMut withObject:mutDic];
                    
                    
                    [_collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:indexMut inSection:0]]];
                //    [_tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForItem:indexMut inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
                }
                
                
            } else {
                [ErrorMessage showErrorMessage:json[@"message"] inView:self.view];
            }
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }];
    } else  {
        //点赞
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        
        NSString*url=[NSString stringWithFormat:FORUM_ZAN_URL_PATH,model.UserID,[value objectForKey:@"ID"],@1];
        NSLog(@"url==%@",url);
        [[HTTPManager standerDefault]AFGetRequest:url view:nil success:^(id json) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            if ([json[@"ret_code"] integerValue]==0) {
                //点赞成功
                int index = (int)[_mutArr indexOfObject:value];
                if (_mutArr.count > index && index >= 0) {
                      MBShowForICell *cell = (MBShowForICell *)[_collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:[NSIndexPath indexPathForItem:index inSection:0]];
                    if ([cell isKindOfClass:[MBShowForICell class]]) {
                        [cell onUpdateZanBtAction:YES];
                    }
                }
                
//                //数据更新
//                [_praiseListArr addObject:@{@"PraisedID":idStr}];
//                NSMutableArray *mutArr = [[NSMutableArray alloc]initWithArray:[UserManager standerDefult].praiseListArr];
//                for (NSDictionary *dic in mutArr) {
//                    NSString *praiseType = [dic objectForKey:@"PraisedType"];
//                    if ([praiseType intValue] == 1) {
//                        [[UserManager standerDefult].praiseListArr removeObject:dic];
//                    }
//                }
//                for (NSDictionary *dic in _praiseListArr) {
//                    NSMutableDictionary *mutDic = [[NSMutableDictionary alloc]initWithDictionary:dic];
//                    [mutDic setValue:@"1" forKey:@"PraisedType"];
//                    [[UserManager standerDefult].praiseListArr addObject:mutDic];
//                }
                //  [mutDic setValue:[NSNumber numberWithInt:1] forKey:@"PraiseStatus"];
                [mutDic setValue:[NSNumber numberWithInt:([[value objectForKey:@"PraiseNum"] intValue]+1)] forKey:@"PraiseNum"];
                [mutDic setValue:@1 forKey:@"PraiseStatus"];
                NSLog(@"mutDci==%@",mutDic);
                if (indexMut < _mutArr.count && indexMut >= 0) {
                    [_mutArr replaceObjectAtIndex:indexMut withObject:mutDic];
                    
                    [_collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:indexMut inSection:0]]];
                }
                
            } else {
                [ErrorMessage showErrorMessage:json[@"message"] inView:self.view];
            }
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }];
    }

    
       _showCell = view;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
//     NSLog(@"点赞1");
//    
//    if ( self.delegate != nil && [self.delegate respondsToSelector:@selector(pushSubViewController:)]) {
    
         NSLog(@"点赞2");
        UserManager *manager = [UserManager standerDefult];
        
        NSString *idStr ;
        if (manager.audioPlayerType != AudioPLayerType_Qinzix) {
            //初次进入
            idStr = @"";
            manager.audioPlayerType = AudioPLayerType_Qinzix;
        } else {
            //2次进入
            NSInteger selectIndex = manager.selectMusicIndex;
            NSArray *arr = manager.musicArr;
            if (arr.count > selectIndex) {
                Music *dics = [arr objectAtIndex:selectIndex];
                idStr = [NSString stringWithFormat:@"%@",dics.ID];
            }
        }
        [manager setSelectMusicIndex:indexPath.row];
        [manager.musicArr removeAllObjects];
        [manager.musicArr addObjectsFromArray:[manager onTurnArrayFormQingZiXiuArray:_mutArr]];
        manager.selectMusicIndex = indexPath.row;
        [manager.qinzixiuArr removeAllObjects];
        [manager.qinzixiuArr addObjectsFromArray:_mutArr];
        

       
        MBDetailViewForIpadController*song=[[MBDetailViewForIpadController alloc]init];
        
                    song.selectMusicID=idStr;
                 [song.dataAllArr addObjectsFromArray:_mutArr];
 
          [self.navigationController pushViewController:song animated:YES];
     
        
  //  }

}
#pragma mark - ScrollView Delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    float y = scrollView.contentOffset.y;
    //    NSLog(@"滑动位移:%.2f",y);
    if (y > 0 && y < 276*PERCEN*2) {
        //隐藏
        if (self.onRecomUIForBlock) {
            if (y >= 276*PERCEN) y = 276*PERCEN;
            self.onRecomUIForBlock(y);
            NSLog(@"隐藏位移:%.2f",y);
        }
    }
    else if ((y < 0 && y > -276*PERCEN)) {
        //显示
        if (self.onRecomUIForBlock) {
            if (y <= 0) y = 0;
            self.onRecomUIForBlock(y);
            //             NSLog(@"****显示位移:%.2f",y);
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
